<?php
(!defined('IN_SYSTEM') || !defined('ADMIN_PRE')) && exit('Access Denied!');
$f = isset($_REQUEST['f'])?$_REQUEST['f']:'index';
if(!ican("region")){
	msg('没有权限');
}
$m = new RegionModule;
$m->$f();
class RegionModule
{
	function index(){
		global $_G;
		$level=0;
		$id= (int)$_REQUEST['rid'];
		$rs=$_G['db']->fetch_one_array("SELECT pid,level FROM".table("region")."WHERE rid=".$id);
		
		$pid=$rs['pid'];
		if(!$pid)$pid=0;
		$level=$rs['level'];
		if(!$level)$level=0;
		if(getGP('regionsubmit','P')){
			$new=getGP('regionnew','P','array');
			$region=getGP('region','P','array');
			if(!empty($region)){
				foreach($region as $k=>$v){
					$v = trim($v);
					if(!$v){
						$ids[$k]=$k;continue;
					}
					if($k){
						$_G['db']->update("region",array("region"=>$v),array("rid"=>$k));
						$idss[$k]=$k;
					}
				}
				if(!empty($ids)){
					//todo 递归删除
					$this->deletechild($ids);
				}
				if(!empty($idss)){
					$sub =  $_G['db']->fetch_all("SELECT rid FROM".table("region")."WHERE rid NOT IN(".implode(',', $idss).") AND pid=".$id);
					if(!empty($sub)){
						$ids=array();
						foreach($sub as $v){
							$ids[$v['rid']]=$v['rid'];
						}
						$this->deletechild($ids);
					}
				}
			}else{//删除子级
				$sub =  $_G['db']->fetch_all("SELECT rid FROM".table("region")."WHERE  pid=".$id);
					if(!empty($sub)){
						$ids=array();
						foreach($sub as $v){
							$ids[$v['rid']]=$v['rid'];
						}
						$this->deletechild($ids);
					}
			}
			if(!empty($new)){
				$level+=1;
				foreach($new as $v){
					$v = trim($v);
					if(!$v)continue;
					$str.=$p."($id, '$v', $level)";
					$p=",";
				}
				if($str)$_G['db']->query("INSERT INTO".table('region')."(pid,region,level) VALUES ".$str.";");
			}
			
			msg("操作成功","admin.php?m=region&rid=".$id);
		}
		
		//上$level级数据
		$lev=$level;
		if($level>0)$level-=1;
			$le=$level;
			$selected[$level]=$id;
			for($i=$level;$i>=0;$i--){
				$datast[$i] = $_G['db']->fetch_all("SELECT rid,region FROM".table("region")."WHERE pid='$pid'");
				$selected[--$le]=$pid;
				$pid=$_G['db']->result("SELECT pid FROM".table("region")."WHERE rid='$pid'");
			}
		//下一级数据
			if($lev>0){
				$datas=$datast[$lev+1] = $_G['db']->fetch_all("SELECT rid,region FROM".table("region")."WHERE pid=".$id);
			}else{
				$datas=$datast[0];
			}
			if(empty($datast[$lev+1]))unset($datast[$lev+1]);
			ksort($datast);
			
			include admintemplate('region');
	}
	function deletechild($ids){
		if(empty($ids))return;
		global $_G;
		while(true){
			$sub =  $_G['db']->fetch_all("SELECT rid FROM".table("region")."WHERE pid IN(".implode(',',$ids).")");
			$_G['db']->query("DELETE  FROM".table('region')." WHERE rid IN(".implode(',', $ids).") ");
			if(!empty($sub)){
				$ids=array();
				foreach($sub as $v){
					$ids[$v['rid']]=$v['rid'];
				}
			}else{
				break;
			}
			
		}
		
	}
}	
?>